#-*- coding: utf-8 -*-
'''
Created on Aug 25, 2012

@author: bbg
'''
import random, time, datetime
from core.db.company_management.cdkey import Cdkey


class CdkeyManager(object):
    '''
    manage CDKEYs
    '''
    
    #cdkey 状态定义：未激活、激活、过期
    CDKEY_INACTIVE = 0
    CDKEY_ACTIVE = 1
    CDKEY_EXPIRED = 2

    @staticmethod
    def generateNewCdkey():
        seeds = 'ABCDEFGHIJKLMNOPJRSTUVSWXYZ1234567890'
        seeds_len = len(seeds)
        
        newCdkey = ''
        
        for i in range(4):
            for j in range(5):            
                idx = random.randint(0, seeds_len - 1)
                newCdkey = newCdkey + seeds[idx]
                time.sleep(0.001)
            if i < 3:
                newCdkey = newCdkey + '-'
            
        return newCdkey
    
    @staticmethod
    def generateCdkeysForCompany(company_id, count, dbsession):
        '''
        generate new cdkeys for a company
        - company_id: company's id
        - count: cdkey's count 
        - session: MySql session
        '''
        
        if dbsession is None:
            return False
        
        for i in range(count):
            newCdkey = CdkeyManager.generateNewCdkey()
            
            cdkey = Cdkey()
            cdkey.company_id = company_id
            cdkey.cdkey = newCdkey
            cdkey.state = CdkeyManager.CDKEY_INACTIVE
            cdkey.shop_id = 0
            cdkey.uuid = ''
            
            #valid date & expired date setting
            #default 1 year
            nowDate = datetime.datetime.now()
            cdkey.valid_time = nowDate.strftime("%Y-%m-%d %H:%M:%S")
            delta = datetime.timedelta(days = 365)
            cdkey.expire_time = (nowDate + delta).strftime("%Y-%m-%d %H:%M:%S")
            
            dbsession.add(cdkey)
            dbsession.commit()
        
        return True
                        
    @staticmethod
    def getCompanyShopIdPair(cdkeyString, dbsession):
        '''
            from cdkey string, find the corresponding company id and shop id,
            return None if not found
        '''         
        if dbsession is None:
            return None
        
        cdkeys = dbsession.query(Cdkey).filter(Cdkey.cdkey == cdkeyString)
        dbsession.commit()
        
        if cdkeys.count() == 0:
            return None
        
        return (cdkeys.first().company_id, cdkeys.first().shop_id, cdkeys.first().state)      
    
    
    @staticmethod
    def getCdkeyInfo(cdkeyString, dbsession):
        if dbsession is None:
            return None
        
        cdkeys = dbsession.query(Cdkey).filter(Cdkey.cdkey == cdkeyString)
        dbsession.commit()
        
        if cdkeys.count() == 0:
            return None
        
        return cdkeys.first()          
    
    @staticmethod
    def checkhasCompanyUUID(uuidString,dbsession):
        '''
               判断UUID是否已经注册使用过
        '''
         
        if dbsession is None:
            return True
        
        cdkeys = dbsession.query(Cdkey).filter(Cdkey.uuid == uuidString)
        dbsession.commit()
        
        if cdkeys.count() == 0:
            return False
        
        return True        
    

    @staticmethod
    def isValid(cdkeyString, uuid,dbsession):
        '''
            判断cdkey状态是否处于激活状态，是否过期，存储的uuid和传入的uuid是否相等，
            如果条件都符合，说明这个cdkey是有效的，return Ture  else return False
        '''
         
        if dbsession is None:
            return False
        
        cdkeys = dbsession.query(Cdkey).filter(Cdkey.cdkey == cdkeyString)
        dbsession.commit()
        
        if cdkeys.count() == 0:
            return False       
        
        cdkey = cdkeys.first()
        nowDate = datetime.datetime.now()
        #expireDate = cdkey.expire_time#datetime.datetime.strptime(cdkey.expire_time, "%Y-%m-%d %H:%M:%S")
        expireDate = datetime.datetime.strptime(cdkey.expire_time, "%Y-%m-%d %H:%M:%S")
        if cdkey.uuid == uuid and cdkey.state == CdkeyManager.CDKEY_ACTIVE and nowDate < expireDate :
            return True
        else:
            return False
        

    @staticmethod
    def bindUuidCDkey(cdkeyString, uuid,dbsession):
        '''
          绑定CDKEY和UUID 
        '''
         
        if dbsession is None:
            return None
        
        cdkeys = dbsession.query(Cdkey).filter(Cdkey.cdkey == cdkeyString).filter(Cdkey.state ==0)
        dbsession.commit()
        
        if cdkeys.count() == 0:
            return None       
        
        cdkeyB = cdkeys.first()
        cdkeyB.uuid=uuid
        cdkeyB.state="1"
        dbsession.commit()
        
        
        return (cdkeyB.company_id, cdkeyB.shop_id,cdkeyB.uuid,cdkeyB.cdkey)        

        
    @staticmethod
    def hasbindUuidCDkey(cdkeyString, uuid,dbsession):
        '''
          绑定CDKEY和UUID 
        '''
         
        if dbsession is None:
            return None
        
        cdkeys = dbsession.query(Cdkey).filter(Cdkey.cdkey == cdkeyString).filter(Cdkey.uuid ==uuid).filter(Cdkey.state ==1)
        dbsession.commit()
        
        if cdkeys.count() == 0:
            return None       
        
        cdkeyB = cdkeys.first()
        nowDate = datetime.datetime.now()
        expireDate = cdkeyB.expire_time
        if nowDate > expireDate :
            return None  
                         
        return (cdkeyB.company_id, cdkeyB.shop_id, cdkeyB.uuid, cdkeyB.cdkey)        

 
 
        
'''    
if __name__ == '__main__':
    try:
        session = dbwrapper.MySqlSession()
        
        print CdkeyManager.generateNewCdkey()
        CdkeyManager.generateCdkeysForCompany(2, 1, session)
        cdkeyString = 'IESYJ-SH2Z3-91ST4-9HXRS'
        ids  = CdkeyManager.getCompanyShopIdPair(cdkeyString, session)
        if ids is not None:
            print '%s map to company id:%d, shop id:%d' % (cdkeyString, ids[0], ids[1])
        else:
            print 'no company and shop mapping found, cdkey %s' % cdkeyString
        
        session.close()
    except TypeError, e:
        print 'CDKEY operation failed, TypeError error %s' % e 
'''

    
        